package com.wyh.controller.g3controller;

import com.wyh.common.result.Result;
import com.wyh.domain.po.g3po.CollectionVerification;
import com.wyh.service.g3service.ArrearsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "欠费账龄分析")
@RestController
@RequestMapping("/Arrears")

public class ArrearsController {

    @Autowired
    private ArrearsService arrearsService;

    @ApiOperation("查找客户")
    @GetMapping("/findcustomername")
    public Result<List<Map<String, Object>>> findcustomername() {
        List<CollectionVerification> collectionVerifications = arrearsService.findcustomername();

        Set<String> customerNameSet = new HashSet<>();
        List<Map<String, Object>> result = new ArrayList<>();

        for (CollectionVerification collectionVerification : collectionVerifications) {
            String customerName = collectionVerification.getCustomername();
            if (!customerNameSet.contains(customerName)) {
                Map<String, Object> customerMap = new HashMap<>();
                customerMap.put("customerName", customerName);
                result.add(customerMap);
                customerNameSet.add(customerName);
            }
        }

        return Result.success(result);
    }

    @ApiOperation("楼盘欠费账龄分析")
    @PostMapping("/arrearsSummary")
    public Result<Map<String, Object>> getArrearsSummary(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        LocalDate currentDate = LocalDate.now();
        String currentMonth = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));

        List<CollectionVerification> collectionVerifications = new ArrayList<>();
        Map<String, Double> totalArrearsMap = new HashMap<>();

        for (String propertyName : propertyNames) {
            List<CollectionVerification> verificationList = arrearsService.findAccountingperiod(propertyName);
            collectionVerifications.addAll(verificationList);
        }

        for (CollectionVerification collectionVerification : collectionVerifications) {
            double totalArrears = calculateTotalArrears(collectionVerification, collectionVerifications);
            totalArrearsMap.put(collectionVerification.getPropertyname(), totalArrears);
        }

        // 对结果按照 totalArrears 降序排序
        Map<String, Double> sortedTotalArrearsMap = totalArrearsMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

        Map<String, Object> result = new LinkedHashMap<>();

        for (Map.Entry<String, Double> entry : sortedTotalArrearsMap.entrySet()) {
            String buildingName = entry.getKey();
            double totalArrears = entry.getValue();
            double arrears1To3Months = calculateArrears1To3Months(collectionVerifications, buildingName, currentMonth);
            double arrears4To6Months = calculateArrears4To6Months(collectionVerifications, buildingName, currentMonth);
            double arrearsOver6Months = calculateArrearsOver6Months(collectionVerifications, buildingName, currentMonth);

            // 获取客户名称

            Map<String, Object> buildingSummary = new HashMap<>();
            buildingSummary.put("buildingName", buildingName);
            buildingSummary.put("totalArrears", totalArrears);
            buildingSummary.put("arrears1To3Months", arrears1To3Months);
            buildingSummary.put("arrears4To6Months", arrears4To6Months);
            buildingSummary.put("arrearsOver6Months", arrearsOver6Months);

            result.put(buildingName, buildingSummary);
        }

        return Result.success(result);
    }

    @ApiOperation("楼盘欠费账龄分析分页")
    @PostMapping("/page")
    public Result<Map<String, Object>> page(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        LocalDate currentDate = LocalDate.now();
        String currentMonth = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        int currentPage = Integer.parseInt((String) request.get("currentPage"));
        int pageSize = Integer.parseInt((String) request.get("pageSize"));

        List<CollectionVerification> collectionVerifications = new ArrayList<>();
        Map<String, Double> totalArrearsMap = new HashMap<>();

        for (String propertyName : propertyNames) {
            List<CollectionVerification> verificationList = arrearsService.findAccountingperiod(propertyName);
            collectionVerifications.addAll(verificationList);
        }

        for (CollectionVerification collectionVerification : collectionVerifications) {
            double totalArrears = calculateTotalArrears(collectionVerification, collectionVerifications);
            totalArrearsMap.put(collectionVerification.getPropertyname(), totalArrears);
        }

        // 对结果按照 totalArrears 降序排序
        Map<String, Double> sortedTotalArrearsMap = totalArrearsMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

        Map<String, Object> result = new LinkedHashMap<>();

        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, sortedTotalArrearsMap.size());

        int index = 0;
        for (Map.Entry<String, Double> entry : sortedTotalArrearsMap.entrySet()) {
            if (index >= startIndex && index < endIndex) {
                String buildingName = entry.getKey();
                double totalArrears = entry.getValue();
                double arrears1To3Months = calculateArrears1To3Months(collectionVerifications, buildingName, currentMonth);
                double arrears4To6Months = calculateArrears4To6Months(collectionVerifications, buildingName, currentMonth);
                double arrearsOver6Months = calculateArrearsOver6Months(collectionVerifications, buildingName, currentMonth);


                Map<String, Object> buildingSummary = new HashMap<>();
                buildingSummary.put("buildingName", buildingName);
                buildingSummary.put("totalArrears", totalArrears);
                buildingSummary.put("arrears1To3Months", arrears1To3Months);
                buildingSummary.put("arrears4To6Months", arrears4To6Months);
                buildingSummary.put("arrearsOver6Months", arrearsOver6Months);

                result.put(buildingName, buildingSummary);
            }
            index++;
        }

        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("total", sortedTotalArrearsMap.size());
        resultMap.put("data", result);

        return Result.success(resultMap);
    }


    @ApiOperation("客户欠费账龄分析")
    @PostMapping("/filterArrearsSummary")
    public Result<Map<String, Object>> filterArrearsSummary(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        String customerName = (String) request.get("customerName");
        LocalDate currentDate = LocalDate.now();
        String currentMonth = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));

        List<CollectionVerification> collectionVerifications = new ArrayList<>();
        Map<String, Double> totalArrearsMap = new HashMap<>();

        for (String propertyName : propertyNames) {
            List<CollectionVerification> verificationList = arrearsService.findAccountingperiods(propertyName,customerName);
            collectionVerifications.addAll(verificationList);
        }

        for (CollectionVerification collectionVerification : collectionVerifications) {
            double totalArrears = calculateTotalArrears(collectionVerification, collectionVerifications);
            totalArrearsMap.put(collectionVerification.getPropertyname(), totalArrears);
        }

        // 对结果按照 totalArrears 降序排序
        Map<String, Double> sortedTotalArrearsMap = totalArrearsMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

        Map<String, Object> result = new LinkedHashMap<>();

        for (Map.Entry<String, Double> entry : sortedTotalArrearsMap.entrySet()) {
            String buildingName = entry.getKey();
            double totalArrears = entry.getValue();
            double arrears1To3Months = calculateArrears1To3Months(collectionVerifications, buildingName, currentMonth);
            double arrears4To6Months = calculateArrears4To6Months(collectionVerifications, buildingName, currentMonth);
            double arrearsOver6Months = calculateArrearsOver6Months(collectionVerifications, buildingName, currentMonth);

            // 获取客户名称

            Map<String, Object> buildingSummary = new HashMap<>();
            buildingSummary.put("buildingName", buildingName);
            buildingSummary.put("customerName", customerName);
            buildingSummary.put("totalArrears", totalArrears);
            buildingSummary.put("arrears1To3Months", arrears1To3Months);
            buildingSummary.put("arrears4To6Months", arrears4To6Months);
            buildingSummary.put("arrearsOver6Months", arrearsOver6Months);

            result.put(buildingName, buildingSummary);
        }

        return Result.success(result);
    }

    @ApiOperation("客户欠费账龄分析分页")
    @PostMapping("/page2")
    public Result<Map<String, Object>> page2(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        String customerName = (String) request.get("customerName");
        LocalDate currentDate = LocalDate.now();
        String currentMonth = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        int currentPage = Integer.parseInt((String) request.get("currentPage"));
        int pageSize = Integer.parseInt((String) request.get("pageSize"));

        List<CollectionVerification> collectionVerifications = new ArrayList<>();
        Map<String, Double> totalArrearsMap = new HashMap<>();

        for (String propertyName : propertyNames) {
            List<CollectionVerification> verificationList = arrearsService.findAccountingperiods(propertyName, customerName);
            collectionVerifications.addAll(verificationList);
        }

        for (CollectionVerification collectionVerification : collectionVerifications) {
            double totalArrears = calculateTotalArrears(collectionVerification, collectionVerifications);
            totalArrearsMap.put(collectionVerification.getPropertyname(), totalArrears);
        }

        // 对结果按照 totalArrears 降序排序
        Map<String, Double> sortedTotalArrearsMap = totalArrearsMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

        Map<String, Object> result = new LinkedHashMap<>();

        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, sortedTotalArrearsMap.size());

        int index = 0;
        for (Map.Entry<String, Double> entry : sortedTotalArrearsMap.entrySet()) {
            if (index >= startIndex && index < endIndex) {
                String buildingName = entry.getKey();
                double totalArrears = entry.getValue();
                double arrears1To3Months = calculateArrears1To3Months(collectionVerifications, buildingName, currentMonth);
                double arrears4To6Months = calculateArrears4To6Months(collectionVerifications, buildingName, currentMonth);
                double arrearsOver6Months = calculateArrearsOver6Months(collectionVerifications, buildingName, currentMonth);

                Map<String, Object> buildingSummary = new HashMap<>();
                buildingSummary.put("buildingName", buildingName);
                buildingSummary.put("customerName", customerName);
                buildingSummary.put("totalArrears", totalArrears);
                buildingSummary.put("arrears1To3Months", arrears1To3Months);
                buildingSummary.put("arrears4To6Months", arrears4To6Months);
                buildingSummary.put("arrearsOver6Months", arrearsOver6Months);

                result.put(buildingName, buildingSummary);
            }
            index++;
        }

        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("total", sortedTotalArrearsMap.size());
        resultMap.put("data", result);

        return Result.success(resultMap);
    }




    @ApiOperation("excel导出（楼盘欠费账龄分析）")
    @PostMapping("/exportFloor")
    private Result<String> exportFloorArrearsAnalysisToExcel(@RequestBody Map<String, Object> request, HttpServletResponse response) throws IOException{
        Result<Map<String, Object>> arrearsSummaryResult = getArrearsSummary(request);
        Map<String, Object> arrearsSummary = arrearsSummaryResult.getData();

        // 创建Excel文件并填入数据
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Arrears Analysis");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("楼盘名称");
        headerRow.createCell(1).setCellValue("欠费总金额");
        headerRow.createCell(2).setCellValue("欠费1-3月");
        headerRow.createCell(3).setCellValue("欠费4-6月");
        headerRow.createCell(4).setCellValue("欠费6月以上");

        // 填入数据
        int rowNum = 1;
        for (Map.Entry<String, Object> entry : arrearsSummary.entrySet()) {
            String buildingName = entry.getKey();
            Map<String, Object> buildingSummary = (Map<String, Object>) entry.getValue();
            String customerName = (String) buildingSummary.get("customerName");
            double totalArrears = (double) buildingSummary.get("totalArrears");
            double arrears1To3Months = (double) buildingSummary.get("arrears1To3Months");
            double arrears4To6Months = (double) buildingSummary.get("arrears4To6Months");
            double arrearsOver6Months = (double) buildingSummary.get("arrearsOver6Months");

            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(buildingName);
            row.createCell(1).setCellValue(totalArrears);
            row.createCell(2).setCellValue(arrears1To3Months);
            row.createCell(3).setCellValue(arrears4To6Months);
            row.createCell(4).setCellValue(arrearsOver6Months);
        }

        // 保存Excel文件到桌面
        String desktopPath = System.getProperty("user.home") + "/Desktop/楼盘欠费账龄分析表.xlsx";
        try (FileOutputStream fileOut = new FileOutputStream(desktopPath)) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success("Excel导出成功，文件路径：" + desktopPath);
    }

    // 导出客户欠费账龄分析表到Excel文件
    @ApiOperation("excel导出（客户欠费账龄分析）")
    @PostMapping("/exportClient")
    public Result<String> exportCustomerArrearsAnalysisToExcel(@RequestBody Map<String, Object> filterRequest) {
        String customerName = (String) filterRequest.get("customerName");
        List<String> propertyNames = (List<String>) filterRequest.get("propertyNames");

        // 获取符合条件的楼盘欠费汇总信息
        Result<Map<String, Object>> filteredArrearsSummaryResult = filterArrearsSummary(filterRequest);
        Map<String, Object> filteredArrearsSummary = filteredArrearsSummaryResult.getData();

        // 创建Excel文件并填入数据
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Customer Arrears Analysis");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("楼盘名称");
        headerRow.createCell(1).setCellValue("客户名称");
        headerRow.createCell(2).setCellValue("欠费总金额");
        headerRow.createCell(3).setCellValue("欠费1-3月");
        headerRow.createCell(4).setCellValue("欠费4-6月");
        headerRow.createCell(5).setCellValue("欠费6月以上");

        // 填入数据
        int rowNum = 1;
        for (Map.Entry<String, Object> entry : filteredArrearsSummary.entrySet()) {
            String buildingName = entry.getKey();
            Map<String, Object> buildingSummary = (Map<String, Object>) entry.getValue();
            String buildingCustomerName = (String) buildingSummary.get("customerName");
            double totalArrears = (double) buildingSummary.get("totalArrears");
            double arrears1To3Months = (double) buildingSummary.get("arrears1To3Months");
            double arrears4To6Months = (double) buildingSummary.get("arrears4To6Months");
            double arrearsOver6Months = (double) buildingSummary.get("arrearsOver6Months");

            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(buildingName);
            row.createCell(1).setCellValue(buildingCustomerName);
            row.createCell(2).setCellValue(totalArrears);
            row.createCell(3).setCellValue(arrears1To3Months);
            row.createCell(4).setCellValue(arrears4To6Months);
            row.createCell(5).setCellValue(arrearsOver6Months);
        }

        // 保存Excel文件到桌面
        String desktopPath = System.getProperty("user.home") + "/Desktop/客户欠费账龄分析表.xlsx";
        try (FileOutputStream fileOut = new FileOutputStream(desktopPath)) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success("Excel导出成功，文件路径：" + desktopPath);
    }



    private double calculateTotalArrears(CollectionVerification currentVerification, List<CollectionVerification> allVerifications) {
        String buildingName = currentVerification.getPropertyname();
        double totalArrears = allVerifications.stream()
                .filter(verification -> verification.getPropertyname().equals(buildingName))
                .mapToDouble(verification -> Double.parseDouble(verification.getArrearsoffees()))
                .sum();
        return totalArrears;
    }

    private double calculateArrears1To3Months(List<CollectionVerification> collectionVerifications, String buildingName, String currentMonth) {
        double arrears1To3Months = 0.0;
        for (CollectionVerification verification : collectionVerifications) {
            if (verification.getPropertyname().equals(buildingName)) {
                int monthsDifference = getMonthsDifference(currentMonth, verification.getAccountingperiod());
                if (monthsDifference >= 0 && monthsDifference <= 3) {
                    arrears1To3Months += Double.parseDouble(verification.getArrearsoffees());
                }
            }
        }
        return arrears1To3Months;
    }

    private double calculateArrears4To6Months(List<CollectionVerification> collectionVerifications, String buildingName, String currentMonth) {
        double arrears4To6Months = 0.0;
        for (CollectionVerification verification : collectionVerifications) {
            if (verification.getPropertyname().equals(buildingName)) {
                int monthsDifference = getMonthsDifference(currentMonth, verification.getAccountingperiod());
                if (monthsDifference > 3 && monthsDifference <= 6) {
                    arrears4To6Months += Double.parseDouble(verification.getArrearsoffees());
                }
            }
        }
        return arrears4To6Months;
    }

    private double calculateArrearsOver6Months(List<CollectionVerification> collectionVerifications, String buildingName, String currentMonth) {
        double arrearsOver6Months = 0.0;
        for (CollectionVerification verification : collectionVerifications) {
            if (verification.getPropertyname().equals(buildingName)) {
                int monthsDifference = getMonthsDifference(currentMonth, verification.getAccountingperiod());
                if (monthsDifference > 6) {
                    arrearsOver6Months += Double.parseDouble(verification.getArrearsoffees());
                }
            }
        }
        return arrearsOver6Months;
    }

    private String getCustomerName(List<CollectionVerification> collectionVerifications, String buildingName) {
        for (CollectionVerification verification : collectionVerifications) {
            if (verification.getPropertyname().equals(buildingName)) {
                return verification.getCustomername();
            }
        }
        return "Unknown";
    }

    private int getMonthsDifference(String currentMonth, String accountingPeriod) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        YearMonth currentYearMonth = YearMonth.parse(currentMonth + "-01", formatter);
        YearMonth periodYearMonth = YearMonth.parse(accountingPeriod + "-01", formatter);
        int Mouths= Math.abs(Period.between(periodYearMonth.atEndOfMonth(), currentYearMonth.atEndOfMonth()).getMonths());
        int Years=Math.abs(Period.between(periodYearMonth.atEndOfMonth(), currentYearMonth.atEndOfMonth()).getYears());
        int Time=Mouths+Years*12;
        return Time;
    }

}